package com.leyou.user.controller;

import com.leyou.auth.dto.UserDetails;
import com.leyou.auth.utils.UserContext;
import com.leyou.common.exception.LyException;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/info")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 查询数据是否存在
     * @param data 要校验的数据
     * @param type 数据的类型，1：用户名，2：手机号
     * @return boolean
     */
    @GetMapping("/exists/{data}/{type}")
    public ResponseEntity<Boolean> queryInfoExist(@PathVariable("data") String data,
                                                 @PathVariable("type") Integer type){
        return ResponseEntity.ok(userService.queryInfoExist(data,type));
    }


    /**
     * 根据用户名和密码查询
     * @param username 用户名
     * @param password 密码
     * @return userDTO
     */
    @GetMapping
    public ResponseEntity<UserDTO> queryUserByUserNameAndPassword(@RequestParam("username") String username,
                                                                  @RequestParam("password") String password){
        return ResponseEntity.ok(userService.queryUserByUserNameAndPassword(username,password));
    }


    /**
     * 发送验证码
     * @param phone 电话号码
     * @return void
     */
    @PostMapping("/code")
    public ResponseEntity<Void> sendMessageCode(@RequestParam("phone") String phone){

        userService.sendMessageCode(phone);

        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }


    /**
     * 注册用户
     * @param user 用户信息
     * @param code 验证码
     * @return 无
     * BindingResult参数，不管校验是否通过，都会进入方法内部
     */
    @PostMapping
    public ResponseEntity<Void> registerUser(@Valid User user, BindingResult result, @RequestParam("code") String code){
        //自定义异常 BindingResult中会封装错误结果
        // 通过result.hashErrors来判断是否有错误
        if (result.hasErrors()) {
            String msg = result.getFieldErrors().stream().map(FieldError::getDefaultMessage)
                    .collect(Collectors.joining("|"));
            throw new LyException(400, msg);
        }

        userService.registerUser(user,code);

        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }


    /**
     * 获取当前登录的用户信息
     * @return 用户信息
     */
    @GetMapping("me")
    public ResponseEntity<UserDetails> me(){
        return ResponseEntity.ok(UserContext.getUser());
    }


}
